<?php
namespace Home\Controller;
use Think\Controller;
use Com\Wxpay\lib\WxPayConfig;
use Com\Wxpay\example\JsApiPay;
use Com\Wechat\TPWechat;

// +----------------------------------------------------------------------
// |===== Pyboon =====
// +----------------------------------------------------------------------
// | Copyright (c) 2016 Pyboon All rights reserved.
// +----------------------------------------------------------------------
// | Author: Baboon <Pyboon@foxmail.com>
// +----------------------------------------------------------------------
// | Date: 2016年1月18日 下午3:25:17
// +----------------------------------------------------------------------
class BaseController extends Controller{
    
    var $SchoolName;
    protected function _initialize(){
        header("Content-type: text/html; charset=utf-8");
        $this->SchoolName = "中国石油大学";//
    }
    public function index(){
       
       $userinfo = D("AdmissionStuInfo");
       print_r($userinfo->limit(0,1)->select());
    }
    
    /** 
    * @describation 根据学校、姓名以及身份证号获取报名信息
    * @param unknowtype
    * @return return_type
    * @author baboon
    * @date 2016年1月22日上午10:19:55
    */
    public function getInfo(){
        
        $SchoolName = $this->SchoolName;//获取学校名称
    }
    
    /** 
    * @describation 获取Sub（报考站点）
    * @param unknowtype
    * @return return_type
    * @author baboon
    * @date 2016年1月22日上午10:23:04
    */
    public function getSub(){
        
        $SchoolName = $this->SchoolName;//获取学校名称
        //获取报考站点
        $model = D("BaseSchoolInfo");//初始化Common模型
       
        $school = $model->where(array("Name"=>$SchoolName))->find();
       
        if($school){
            $model = D("BaseSubInfo");//初始化Common模型
           
            $sublist = $model->where(array("SchoolID"=>$school["Id"]))->select();
           
            return $sublist;
        }
        return null;
    }
    
    /** 
    * @describation 获取Level（层次）
    * @param unknowtype
    * @return return_type
    * @author baboon
    * @date 2016年1月22日上午10:46:17
    */
    public function getLevel(){
        
        $returnData = array();
        $subID = I("subID");//"81213e52-2567-4b0e-9d93-ed1f229499cb";//$this->getSub();//"";//
        //$subID = $subID[99]["Id"];
        $model = D("BaseSubInfo");
        $sub = $model->where(array("Id"=>$subID))->find();
       // print_r($sub);
        if($sub){
            $model = D("AdmissionBatchInfo");
           
            $con["SchoolID"] = $sub["SchoolID"];
          //  $con["IsEnabled"] = 1;//IsEnabled直接放在$con中无法查询
          
            $batch = $model->where("IsEnabled = 1")->where($con)->select();
           // print_r($model->getLastSql());
            unset($con);
            //print_r($batch);
            if($batch){
                $model = D("ViewAdmissionBatchSubPlanInfo");
                $levellist = $model->where("AuditStatus='审核通过'")->where(array("SubID"=>$subID,
                    "BatchID"=>$batch[0]["Id"]))->field("StuLevel")->distinct(true)->select();
                //print_r($model->getLastSql());
                $returnData["status"] = 200;
                $returnData["status"] = 200;
                $returnData["levellist"] = $levellist;
                $this->ajaxReturn($returnData);
            }
            else {
                $returnData["status"] = 301;
                $returnData["message"] = "未取到batchlist";
                $this->ajaxReturn($returnData);
            }
                
        }
        else {
            $returnData["status"] = 300;
            $returnData["message"] = "未取到sublist";
            $this->ajaxReturn($returnData);
        }
    }
    
    /** 
    * @describation 获取Major（专业）
    * @param unknowtype
    * @return return_type
    * @author baboon
    * @date 2016年1月22日上午11:13:30
    */
    public function getMajor(){
        $returnData = array();
        $subID = I("subID");//"81213e52-2567-4b0e-9d93-ed1f229499cb";//I("SubID");
        $StuLevel = I("StuLevel");//"网络春专升本";//I("StuLevel");
        $model = D("BaseSubInfo");
       
        $sub = $model->where(array("Id"=>$subID))->find();
        if($sub){
            $model = D("AdmissionBatchInfo");
            
            $batch = $model->where("IsEnabled = 1")->where(array("SchoolID"=>$sub["SchoolID"]))->select();
            if($batch){
                $model = D("ViewAdmissionBatchSubPlanInfo");
                
                $majorlist = $model->where("AuditStatus='审核通过'")->where(array("SubID"=>$subID,
                    "BatchID"=>$batch[0]["Id"],"StuLevel"=>$StuLevel))->distinct(true)->select();
               // print_r($model->getLastSql());
                $returnData["status"] = 200;
                $returnData["majorlist"] = $majorlist;
                $this->ajaxReturn($returnData);
            }
            else {
                $returnData["status"] = 301;
                $returnData["message"] = "未取到batchlist";
                $this->ajaxReturn($returnData);
            }
            
        }
        else {
            $returnData["status"] = 300;
            $returnData["message"] = "未取到sublist";
            $this->ajaxReturn($returnData);
        }
        
    }
    
    
    public function signUp(){
        $options = array(
           'appid'=>C("Academic_WXAPPID"),
           'secret'=>C("Academic_WXAPPSECRET"),
       );
        $wxpaycfg = new WxPayConfig($options);
        $tools = new JsApiPay($wxpaycfg);
        $openid = $tools->GetOpenid();
        session("openid",$openid);
        $this->assign('sublist',$this->getSub());
        $this->display("StuInfo:signUp");
         
    }
    public function insertStuInfo(){
        
        $post_data = I("post.");
        $return_data = array();
        $insert_data = array();
         if(trim($post_data["Name"])==""){
            $return_data["status"] = 301;
            $return_data["message"] = "姓名不能为空";
            $this->ajaxReturn($return_data);
        } 
         $pattern = "/^1[3|4|5|7|8][0-9]\d{8}$/";
        if(!preg_match($pattern, $post_data["Phone"])){
            $return_data["status"] = 301;
            $return_data["message"] = "手机号码格式不正确";
            $this->ajaxReturn($return_data);
        }
        
        $pattern = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        if($post_data["CardType"] =="身份证"){
            if(!preg_match($pattern, $post_data["CardNum"])){
                $return_data["status"] = 301;
                $return_data["message"] = "身份证号格式不正确";
                $this->ajaxReturn($return_data);
            }
            else {
                $post_data["BirthDay"] = substr($post_data["CardNum"],6,4)."-"
                    .substr($post_data["CardNum"],10,2)."-".substr($post_data["CardNum"],12,2);
                if(substr($post_data["CardNum"],14,3) % 2 == 0){
                    $post_data["Sex"] = "女";
                }
                else {
                    $post_data["Sex"] = "男";
                }
            }
        } 
       
        $model = D("BaseSubInfo");
      
        $sub = $model->where(array("Id"=>$post_data["SubID"]))->find(); 
        if($sub){
            $model = D("AdmissionBatchInfo");
           
            $con["SchoolID"] = $sub["SchoolID"];
            //  $con["IsEnabled"] = 1;//IsEnabled直接放在$con中无法查询
            $batch = $model->where("IsEnabled = 1")->where($con)->find();
            unset($con);
            if($batch){
                $model = D("AdmissionStuInfo");
                
                $stuinfo = $model->where(array("CardNum"=>$post_data["CardNum"],
                    "BatchID"=>$batch["Id"]))->find();
                if($stuinfo){
                    $return_data["status"] = 310;
                    $return_data["message"] = "请勿重复报名";
                    $this->ajaxReturn($return_data);
                }
                else {
                   $post_data["SchoolID"] = $sub["SchoolID"]; 
                   $post_data["BatchID"] = $batch["Id"];
                   $db_fields = $model->getDbFields();
                   foreach ($post_data as $key => $value) {
                       if(in_array_case($key, $db_fields)){
                           $insert_data[$key] = $post_data[$key];
                       }
                   }
                  
                   $detail = explode("#",$post_data["MajorID_LevelID"]);
                   $insert_data["MajorID"] = $detail[0];
                   $insert_data["StuLevelID"] = $detail[1];
                   $insert_data["Id"] = NewGuid();
                   $insert_data["DateCreated"] = date("Y-m-d H:i:s");
                   $insert_data["IsPass"] = false;
                   $insert_data["IsIDCardConfirmed"] = false;
                   $insert_data["InfoAuditStatus"] = "未确认";
                   $insert_data["RegistType"] = 1;
                   $insert_data["EnrolmentMethod"] = 3;
                   //报名序号的生成
                   ////
                   if($model->add($insert_data)!==false){
                   
                       $return_data["status"] = 200;
                       $return_data["message"] = "报名成功";
                       $return_data["url"] = U("Base/signUpSuccess");
                       $info = D("ViewAdmissionStuInfo")->where(array("Id"=>$insert_data["Id"]))->find();
                       //微信发送通知
                       $TMdata = array();
                       $TMdata["url"] = "";
                       $TMdata["first"] = "您好，您已经报名成功！";
                       $TMdata["keyword1"] = "请前往学习中心获取";//$info["Num"];
                       $TMdata["keyword2"] = $info["Name"];
                       $TMdata["keyword3"] = $info["SubName"];
                       $TMdata["keyword4"] = $info["StuLevel"];
                       $TMdata["keyword5"] = $info["MajorName"];
                       $TMdata["remark"] = "请前往学习中心完善报名信息";
                       $openid = session("openid");
                       wechatMsg($TMdata, $openid,2);
                       $this->ajaxReturn($return_data);
                   }
                   else {
                       $return_data["status"] = 300;
                       $return_data["message"] = "报名失败";
                        
                       $this->ajaxReturn($return_data);
                   
                   }
                }
            }
            
        }
      
        
    }
    public function signUpSuccess(){
        
        $this->display("StuInfo:signUpSuccess");
    }
   
    public function bindUser(){
        $options = array(
           'appid'=>C("Academic_WXAPPID"),
           'secret'=>C("Academic_WXAPPSECRET"),
       );
        $wxpaycfg = new WxPayConfig($options);
        $tools = new JsApiPay($wxpaycfg);
        $openid = $tools->GetOpenid();
        $model = D("User");
        $myUser = $model->where(array("openid"=>$openid))->find();
        if($myUser){
            $this->assign("isBind",true);
            $user = D("ViewAccountStuInfo")->where(array("StuNo"=>$myUser["username"]))->find();
            $this->assign("user",$user);
            $this->assign("openid",$openid);
        }
        else {
            $this->assign("isBind",false);
            $this->assign("openid",$openid);
            $school = D("BaseSchoolInfo")->select();
            $this->assign("school",$school);
        }
        
        $this->display("StuInfo:bindUser");
    }
    
    public function unbind(){
        $openid = I("openid");
        $return_data = array();
        if(!empty($openid)){
            $model = M("User");
            $user = $model->getByOpenid($openid);
            if($user){
                $model->where(array("openid"=>$openid))->delete();
                $return_data["status"] = 200;
                $return_data["message"] = "解绑成功";
                $return_data["url"] = U("Home/Base/bindUser");
            }
            else {
                $return_data["status"] = 301;
                $return_data["message"] = "无user";
            }
            
        }
        else {
            $return_data["status"] = 300;
            $return_data["message"] = "无openid";
        }
        $this->ajaxReturn($return_data);
    }
    
    public function insertBind(){
        
        $return_data = array();
        $openid = I("openid");
        $schoolCode = I("schoolCode");
        $username = I("username");
        $pwd = I("pwd");
        
        if(!empty($openid) && !empty($schoolCode) && !empty($username) && !empty($pwd)){
            //$pwd = md5($pwd);
            $user = D("BaseUser")->where(array("UserName"=>$schoolCode.$username,"Password"=>md5($pwd)))->find();
            if($user){
                
                $model = D("User");
                $myUser = $model->where(array("UserName"=>$username))->find();
                if($myUser){
                    $return_data["status"] = 201;
                    $return_data["message"] = "该账号已经被绑定！";
                }
                else{
                    $insert_data=array();
                    $insert_data["UserName"] = $username;
                    $insert_data["schoolCode"] = $schoolCode;
                    $insert_data["Password"] = $pwd;
                    $insert_data["openid"] = $openid;
                    $insert_data["stuid"] = $user['Id'];
                    if($model->create($insert_data)){
                        if($model->add()!==false){
                            $return_data["status"] = 200;
                            $return_data["message"] = "绑定成功";
                            $return_data["url"] = U("Home/Base/bindSuccess");
                            //微信发送通知
                            $TMdata = array();
                            $TMdata["url"] = "";
                            $TMdata["first"] = "您已经成功绑定平台账户";
                            $TMdata["keyword1"] = $insert_data["UserName"];
                            $TMdata["keyword2"] = "绑定账户后可以免登录直接进入在线学习界面";
                            $TMdata["remark"] = "如需解绑请通过本公众号菜单操作解绑";
                            wechatMsg($TMdata, $openid,1);
                        }
                        else {
                            $return_data["status"] = 202;
                            $return_data["message"] = "绑定失败，请重新绑定";
                        }
                    }
                    else {
                        $return_data["status"] = 203;
                        $return_data["message"] = "绑定失败，请重新绑定";
                    }
                    
                }
             //   oby8TsyPxUauz_zOq4bED-GZ_R3s
            }
            else {
                $return_data["status"] = 300;
                $return_data["message"] = "用户名或密码错误";
            }
            
        }
        else {
            $return_data["status"] = 300;
            $return_data["message"] = "缺失数据";
        }
       $this->ajaxReturn($return_data); 
    }
    
    public function bindSuccess(){
        $this->display("StuInfo:bindSuccess");
    }
   
    
    /** 
    * @describation 在线作业入口
    * @param unknowtype
    * @return return_type
    * @author baboon
    * @date 2016年2月23日下午2:42:38
    */
   public function onlineWork(){
       
       $options = array(
           'appid'=>C("Academic_WXAPPID"),
           'secret'=>C("Academic_WXAPPSECRET"),
       );
       $wxpaycfg = new WxPayConfig($options);
       $tools = new JsApiPay($wxpaycfg);
       $openid = $tools->GetOpenid();
       if($openid){
           $user = D("User")->getbyOpenid($openid);
           if($user){
               $usename = $user["username"];
               $pwd = $user["password"];
               $schoolCode = $user["schoolcode"];
               $base = "http://x.sdcen.cn/mobile/mobileLogin/wxlogin?";
               $url = $base."schoolCode=".$schoolCode."&username=".$usename."&pwd=".$pwd;
               //http://x.upol.cn/mobile/mobileLogin/wxlogin?schoolCode=10425&username=16156104000&pwd=260498
               Header("Location:".$url);
           }
           else{
               $this->redirect('Base/bindUser');
               
           }
       }
       
   }
   
   
}